#ifndef __LIST_H__
#define __LIST_H__

#ifndef offsetof
#define offsetof(type, member) ((size_t) & ((type *)0)->member)
#endif
#define container_of(ptr, type, member) (type *)((char *)ptr - offsetof(type, member))
#define list_entry(ptr, type, member) container_of(ptr, type, member)

typedef struct list_head_st
{
    struct list_head_st *prev, *next;
} list_head_t;

static void list_init(list_head_t *head)
{
    head->prev = head;
    head->next = head;
}

static void __list_add(list_head_t *new_node, list_head_t *pre, list_head_t *nxt)
{
    pre->next = new_node;
    new_node->next = nxt;
    nxt->prev = new_node;
    new_node->prev = pre;
}
/// @brief 类似于栈(可以插队的栈)
/// @param head
/// @param new_node
static void list_add_first(list_head_t *head, list_head_t *new_node)
{
    __list_add(new_node, head, head->next);
}

/// @brief 类似于队列(可以插队的队列)
/// @param head
/// @param new_node
static void list_add_tail(list_head_t *head, list_head_t *new_node)
{
    __list_add(new_node, head->prev, head);
}

static list_head_t *list_del(list_head_t *node)
{
    node->prev->next = node->next;
    node->next->prev = node->prev;
    list_init(node);
    return node;
}

static void list_replace(list_head_t *old_node, list_head_t *new_node)
{
    new_node->next = old_node->next;
    new_node->prev = old_node->prev;
    old_node->prev->next = new_node;
    old_node->next->prev = new_node;
    list_init(old_node);
}

static int list_is_empty(list_head_t *head)
{
    return head == head->next;
}

// 不安全遍历
#define list_for_each_next(head, item) for (item = head->next; item != head; item = item->next)
#define list_for_each_prev(head, item) for (item = head->prev; item != head; item = item->prev)

// 安全遍历 nuseptr为临时变量(不建议动)
#define list_for_each_next_safe(head, item, nuseptr) for (item = (head)->next, nuseptr = item->next; item != (head); item = nuseptr, nuseptr = item->next)
#define list_for_each_prev_safe(head, item, nuseptr) for (item = (head)->prev, nuseptr = item->prev; item != (head); item = nuseptr, nuseptr = item->prev)

#endif